package com.boyou.sytzc.api.core

import android.annotation.SuppressLint
import android.content.Context
import com.boyou.sytzc.BuildConfig
import com.boyou.sytzc.data.entity.ResponseModel
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import com.google.gson.stream.MalformedJsonException
import com.jakewharton.retrofit2.adapter.rxjava2.HttpException
import io.reactivex.Observable
import io.reactivex.ObservableTransformer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import java.lang.reflect.Proxy
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException

/**
 * 处理网络请求结果
 *
 * @param composer 默认为null
 * @param funOnPubResultEvent 结果回调方法
 */
@SuppressLint("CheckResult")
fun <T : ResponseModel> Observable<out T>.handleResult(
	composer: ObservableTransformer<in T, out T>? = null,
	funOnPubResultEvent: (isSuccessful: Boolean, message: String?, result: T?) -> Unit
): Disposable? {
	val instance = subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
	val newInstance = if (composer != null) instance.compose(composer) else instance
	return newInstance.subscribe({ funOnPubResultEvent(/*it.status == */true, it.message, it) }) {
		if (BuildConfig.DEBUG) println("API错误信息：${it.message}")
		val message = (when (it) {
			is UnknownHostException -> "无法解析主机：${it.message?.removePrefix("Unable to resolve host")?.replace(
				":.*".toRegex(),
				"，没有与主机名相关联的地址"
			)}"
			is SocketTimeoutException -> "请求超时, 请稍后重试~"
			is ConnectException -> "链接到${it.message?.removePrefix("Failed to connect to")} 失败"
			is HttpException -> when {
				it.message?.contains("HTTP 404 Not Found".toRegex(RegexOption.IGNORE_CASE)) == true -> "访问的接口不存在~"
				else -> null
			}
			is MalformedJsonException -> "Gson数据解析异常~"
			else -> null
		}) ?: "请求数据失败(${it.message})，请稍后重试~"
		funOnPubResultEvent(false, message.replace("(null)", ""), null)
	}
}